package com.example.autopia.view.Adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.autopia.databinding.ViewholderMyCarsAddBinding
import com.example.autopia.databinding.ViewholderMyCarsBinding
import com.example.autopia.model.Item.Car
import com.example.autopia.view.Listeners.MyCarsListener
import com.example.autopia.view.ViewHolders.MyCars.AddMyCarsViewHolder
import com.example.autopia.view.ViewHolders.MyCars.MyCarViewHolder

class MyCarAdapter :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var oldList = emptyList<Car>().toMutableList()
    private lateinit var listener: MyCarsListener

    fun attachListener(listener: MyCarsListener) {
        this.listener = listener
    }


    fun deletePost(item: Car) {
        val pos = oldList.indexOf(item)
        oldList.removeAt(pos)
        notifyItemRemoved(pos)
    }

    companion object {
        const val CAR_VIEW = 0
        const val ADD_VIEW = 1
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return when (viewType) {
            CAR_VIEW -> MyCarViewHolder(
                ViewholderMyCarsBinding.inflate(
                    LayoutInflater.from(
                        parent.context
                    ), parent, false
                ),inflater
            )

            ADD_VIEW -> AddMyCarsViewHolder(
                ViewholderMyCarsAddBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                ),inflater
            )
            else -> throw IllegalArgumentException("invalid item type")
        }
    }

    override fun getItemCount(): Int {
        return oldList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        return when (oldList[position].viewtype) {
            CAR_VIEW -> (holder as MyCarViewHolder).bind(
                oldList[position],listener
            )
            ADD_VIEW -> (holder as AddMyCarsViewHolder).bind(
                oldList[position],listener
            )
            else -> throw IllegalArgumentException("invalid item type")
        }
    }

    override fun getItemViewType(position: Int): Int {
        return oldList[position].viewtype
    }

    fun setData(newList: List<Car>) {
        oldList = newList.toMutableList()
        notifyDataSetChanged()
    }
}